<style scoped lang="scss">
.user {
  width: 10rem;
  height: 100vh;
  overflow: hidden;

  .user-header {
    width: 10rem;
    height: 22.5vh;
    background-color: pink;
    transition: height 0.5s ease, transform 0.5s ease;
    transform-origin: top center;
    overflow: hidden;

    img {
      width: 10rem;
      height: 22.5vh;
      object-fit: cover;
      transition: height 0.5s ease;
    }
  }

  .user-info {
    width: 10rem;
    height: 77.5vh;
    background-color: #161622;
    position: relative;
    color: $color-white;

    .user-avatar-box {
      width: 9rem;
      height: 2.1333rem;
      position: absolute;
      top: -.4rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 .5rem;

      .user-avatar {
        width: 2.1333rem;
        height: 2.1333rem;
        border-radius: 50%;
        overflow: hidden;
        background: #161622;
        padding: .1333rem;


        img {
          width: 2.1333rem;
          height: 2.1333rem;
          object-fit: cover;
          border-radius: 50%;
          background: #161622;
        }
      }

      button {
        width: 1.8667rem;
        height: .6667rem;
        background: #f8355f;
        border: 0;
        color: $color-white;
        @include flex-center;
        border-radius: .1333rem;
      }
    }

    .user-name {
      padding-top: 2rem;

      h6 {
        font-size: .5333rem;
        margin-left: .5rem;
        font-weight: 700;
      }

      p {
        font-size: .32rem;
        margin-left: .5rem;
        font-weight: 400;
      }
    }

    .user-signature {
      width: 9.5rem;
      margin: 0 auto;
      border-top: 1px solid #222222;
      margin-top: .2rem;
      padding-top: .2rem;

      p {
        font-size: .3733rem;
        font-weight: 400;
        color: #8b8c96;
      }

      span {
        margin-top: .2rem;
        width: 1.5rem;
        height: .2667rem;
        display: inline-block;
        background-color: #43333fb3;
        padding: .1333rem .2133rem;
        border-radius: .1333rem;
        font-size: .2667rem;
        text-align: center;
        display: flex;
        align-items: center;
        color: #8b8c96;

        i {
          color: #da6969;
          font-size: .2667rem;
          margin-right: .1rem;
        }
      }
    }

    .user-follow {
      width: 5.3333rem;
      height: .4rem;
      margin-left: 0.25rem;
      margin-top: .2rem;
      @include flex-space-between-center;

      .user-follow-item {
        height: .3733rem;
        display: flex;
        font-size: .3733rem;
        cursor: pointer;

        span {
          margin-left: .1rem;
          color: #8b8c96;
        }
      }
    }

    .user-dynamic {
      width: 10rem;
      height: 1.12rem;
      display: flex;
      margin-top: .2667rem;
      font-size: .4267rem;
      position: relative;

      .user-dynamic-item {
        width: 3.3333rem;
        height: 1.12rem;
        @include flex-center;
        cursor: pointer;

        span {
          color: #8b8c96;
          margin-right: .1rem;
        }
      }

      .user-follow-line {
        bottom: 0;
        left: 0;
        width: 3.3333rem;
        height: .0533rem;
        background-color: #face15;
        position: absolute;
        top: 1.12rem;
        transition: all .3s;
        z-index: 999;
      }
    }
  }

  .user-back-btn {
    position: absolute;
    top: .3rem;
    left: .3rem;
    width: .8rem;
    height: .8rem;
    border-radius: 50%;
    background: rgba(22, 24, 35, 0.6);
    color: $color-white;
    cursor: pointer;
    @include flex-center;
    z-index: 999;

    i {
      font-size: .35rem;
    }
  }
}

.buttonActive {
  background: #383b44 !important;
}
</style>
<template>
  <div class="user">
    <!-- 左上角返回按钮 -->
    <div class="user-back-btn" @click="$emit('click-back')">
      <i class="iconfont icon-fanhui"></i>
    </div>

    <!-- 主内容区（含滑动缩放） -->
    <div class="user-box" :style="{ transform: `translateY(${swipeY}px)` }" ref="userBoxRef">
      <!-- 头部背景图 -->
      <div class="user-header" :style="{
        height: `${22.5 * bgScale}vh`,
        transform: `scale(${bgScale})`,
        transformOrigin: 'center center'
      }">
        <img :src="userInfo.bgImg || defaultBgImg" alt="背景图" :style="{ height: `${22.5 * bgScale}vh` }">
      </div>



      <!-- 个人信息区 -->
      <div class="user-info">
        <!-- 头像 -->
        <div class="user-avatar-box">
          <div class="user-avatar">
            <img :src="userInfo.userAvatar ? `${imgBaseUrl}${userInfo.userAvatar}` : defaultAvatar" alt="用户头像">
          </div>
          <button :class="{ 'buttonActive': userInfo.myRelation === 'both' || userInfo.myRelation === 'follow' }"
            @click="handleFollowClick">{{
              userInfo.myRelation
                === 'both' ? '互相关注' : userInfo.myRelation === 'follow' ? '已关注' : '关注' }}</button>
        </div>
        <!-- 名称和ID -->
        <div class="user-name">
          <h6>{{ userInfo.userNickname }}</h6>
          <p>抖音号：{{ userInfo.userId }}</p>
        </div>

        <!-- 个性签名和基本信息 -->
        <div class="user-signature">
          <p>{{ userInfo.userDesc || '暂无个性签名' }}</p>
          <span v-if="userInfo.userAge || userInfo.userGender">
            <i class="iconfont" :class="userInfo.userGender === '女' ? 'icon-nv' : 'icon-nan'"></i>
            {{ userInfo.userAge }}岁 {{ userInfo.userGender }}
          </span>
        </div>

        <!-- 统计数据（获赞/关注/粉丝） -->
        <div class="user-follow">
          <div class="user-follow-item">
            <p>{{ userStats.likesNum || 0 }}</p>
            <span>获赞</span>
          </div>
          <div class="user-follow-item" @click="routerClick('/user/follows')">
            <p>{{ userStats.followersNum || 0 }}</p>
            <span>关注</span>
          </div>
          <div class="user-follow-item" @click="routerClick('/user/fans')">
            <p>{{ userStats.fansNum || 0 }}</p>
            <span>粉丝</span>
          </div>
        </div>

        <!-- 内容标签切换（作品/动态/喜欢） -->
        <div class="user-dynamic">
          <div class="user-dynamic-item" @click="getUserVideos">
            <span>作品</span>
            <p>{{ userStats.videosNum || 0 }}</p>
          </div>
          <div class="user-dynamic-item" @click="getUserDynamicVideos">
            <span>动态</span>
            <p>{{ userStats.videosNum || 0 }}</p>
          </div>
          <div class="user-dynamic-item" @click="getUserLikes">
            <span>喜欢</span>
            <p>{{ userStats.likesNum || 0 }}</p>
          </div>
          <!-- 标签切换条 -->
          <div class="user-follow-line" :style="{ left: indexUser * 3.3333 + 'rem' }"></div>
        </div>

        <!-- 内容展示区 -->
        <div class="user-content" v-if="indexUser === 0 || indexUser === 2">
          <UserContentGrid :gridArr="indexUser === 0 ? userVideos : userLikes" @play="isVideo = true" />
        </div>
        <div class="user-dynamic-list" v-if="indexUser === 1">
          <UserDynamicCard :currentVideo="userDynamicVideos" />
        </div>
      </div>
    </div>
  </div>
  <div class="video">
    <shortVideoPlayer :visible="isVideo" :videoList="userVideos" @back="isVideo = false" :videoItemKey="videoItemKey" />
  </div>
  <div class="user-follow-page">
    <router-view></router-view>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { useUserStore } from "@/store/modules/user/user";
import { getUserProfileAPI } from '@/api/user/user';
import { getUserVideosAPI, getUserDynamicVideosAPI, getUserLikedVideosAPI } from '@/api/user/user';
import UserContentGrid from './UserContentGrid.vue';
import UserDynamicCard from './UserDynamicCard.vue';
import { useFingerSwipe } from '../../hooks/useFingerSwipe';
import { triggerFollowAPI } from '@/api/message/message';
import { getCurrentInstance } from 'vue';
import { initUserInfo } from '@/service/userService';
import shortVideoPlayer from '../../components/common/shortVideoPlayer.vue'
import { useRouter } from 'vue-router'
import { useSocketInteractions } from '@/hooks/useSocketInteractions'
const { sendFollow } = useSocketInteractions()

const router = useRouter()
const { proxy } = getCurrentInstance();
// 组件接收的参数（userId 可选，默认用 store 中的用户 ID）
const props = defineProps({
  userId: {
    type: [String, Number],
    default: null // 默认值在 setup 中处理
  },
  // 图片基础路径（方便切换环境）
  imgBaseUrl: {
    type: String,
    default: 'http://43.138.15.137:3000'
  },
  // 默认背景图（无自定义背景时使用）
  defaultBgImg: {
    type: String,
    default: 'http://43.138.15.137/assets/img/281578538336_.pic_hd.e816ad71.jpg'
  },
  // 默认头像（无自定义头像时使用）
  defaultAvatar: {
    type: String,
    default: 'https://img.example.com/default-avatar.png'
  }
});
watch(() => props.userId, (newUserId) => {
  if (newUserId) {
    currentUserId.value = newUserId;
    console.log('userId:', currentUserId.value);
    loadUserInfo(currentUserId.value);
  }
});
// 组件内部状态
const userStore = useUserStore();
const userInfo = ref({}); // 用户信息
const userVideos = ref([]); // 作品列表
const userDynamicVideos = ref([]); // 动态列表
const userLikes = ref([]); // 喜欢列表
const indexUser = ref(null); // 当前激活的标签索引
const isMenuActive = ref(false); // 菜单是否显示
const userBoxRef = ref(null); // 主容器引用
const bgScale = ref(1); // 背景图缩放比例
const swipeY = ref(0); // 滑动距离
// 用户作品动态喜欢获赞关注粉丝数量 统计数据
const isVideo = ref(false); // 视频是否显示
const videoItemKey = ref('Video') // video小写和大写Video视频字符串
const userStats = ref({
  videosNum: 0,
  likesNum: 0,
  followersNum: 0,
  fansNum: 0
});
// 处理默认 userId（优先用 props，否则用 store 中的）
const currentUserId = ref(props.userId || userStore.userInfo.userId);

// 初始化滑动缩放逻辑
const initSwipe = () => {
  if (!userBoxRef.value) return;
  const { y } = useFingerSwipe(userBoxRef.value);
  watch(y, (newY) => {
    if (newY < 0) {
      swipeY.value = newY;
    }
    if (newY >= 0) {
      bgScale.value = 1 + newY * 0.01;
      if (bgScale.value > 1.5) bgScale.value = 1.5; // 限制最大缩放
    } else {
      bgScale.value = 1; // 下拉时恢复
    }
  });
};

// 获取用户信息
const fetchUserInfo = async () => {
  if (!currentUserId.value) return;
  const res = await getUserProfileAPI(currentUserId.value, userStore.userInfo.userId);

  userInfo.value = res.data;
  console.log('获取用户信息:', userInfo.value);
  console.log('myRelation:', userInfo.value.myRelation);
};

// 获取用户作品列表
const getUserVideos = async () => {
  if (indexUser.value === 0) return;
  const res = await getUserVideosAPI(currentUserId.value, 1);
  if (res.code === 200) {
    userVideos.value = res.data;
  }
  indexUser.value = 0;
  console.log(indexUser.value);
};

// 获取用户动态视频列表
const getUserDynamicVideos = async () => {
  if (indexUser.value === 1) return;
  const res = await getUserDynamicVideosAPI(currentUserId.value, 1);
  if (res.code === 200) {
    userDynamicVideos.value = res.data;
  }
  indexUser.value = 1;
};

// 获取用户喜欢列表
const getUserLikes = async () => {
  if (indexUser.value === 2) return;
  const res = await getUserLikedVideosAPI(currentUserId.value, 1);
  if (res.code === 200) {
    userLikes.value = res.data;
    console.log(userLikes.value);
  }
  indexUser.value = 2;
  console.log(indexUser.value);
};

// 监听 userId 变化（如从查看自己切换到查看他人）
watch(currentUserId, async (newId) => {
  if (newId) {
    const res = await loadUserInfo(newId);
    userStats.value = res;
    console.log('用户统计数据:', userStats.value);

    await getUserVideos(); // 重新加载内容
  }
});
// 处理关注/取消关注点击
const handleFollowClick = async () => {
  if (!currentUserId.value) return;
  // 发送Socket关注事件
  sendFollow({
    toUserId: currentUserId.value
  })
  const res = await triggerFollowAPI(userStore.userInfo.userId, currentUserId.value);
  console.log('关注/取消关注:', res);
  // 处理成功响应
  if (res.code === 200) {
    // fan 被关注
    // none 关注
    // follow 互相关注
    // both 互相关注
    const currentStatus = userInfo.value.myRelation;
    proxy.$toast({ message: res.data });
    switch (currentStatus) {
      case 'none':
        userInfo.value.myRelation = 'follow'; // 未关注→已关注
        break;
      case 'follow':
        userInfo.value.myRelation = 'none'; // 已关注→取消关注
        break;
      case 'fan':
        userInfo.value.myRelation = 'both'; // 被关注→互相关注
        break;
      case 'both':
        userInfo.value.myRelation = 'fan'; // 互相关注→取消关注（仅自己取消）
        break;
      default:
        console.log('未知的关注状态:', currentStatus);
    }
  }
};
const routerClick = (path) => {
  router.push({
    path: path,
    query: { userId: currentUserId.value, title: userInfo.value.userNickname }
  });
};




// 组件挂载时初始化用户信息
async function loadUserInfo(userId) {
  const res = await initUserInfo(userId);
  userStats.value = res;
  console.log('用户统计数据1231:', userStats.value);
}
onMounted(async () => {
  await loadUserInfo(currentUserId.value);
  await fetchUserInfo();
  await getUserVideos(); // 初始加载作品
  initSwipe();
  document.body.style.overflow = 'hidden'; // 禁止页面滚动
});

onUnmounted(() => {
  document.body.style.overflow = 'auto'; // 恢复滚动
});

// 暴露事件：菜单点击、内容播放、关注/粉丝点击等
defineEmits([
  'play-content', // 内容播放
  'click-follows', // 点击关注
  'click-fans', // 点击粉丝
  'click-back', // 点击返回
]);
</script>
